<template>
    <q-card class="bg-black">
      <q-bar>
        Logs
        <q-space/>
      </q-bar>
      <q-scroll-area style="height: 470px;">
      <shell :banner="banner" :shell_input="send_to_terminal" @shell_output="prompt"></shell>
      </q-scroll-area>
    </q-card>
</template>
<script>

import shell from './terminal/v-shell'
import TerminalCommandsUtil from "components/terminal/utils/TerminalCommandsUtil"

export default {
  name: 'LogTerminal',
  components: { shell },
  props: {
    dialog: {},
    maximizedToggle: {},
    hideLog: {},
    uuid: {}
  },
  watch: {
    uuid: function (newVal, oldVal) {
      this.terminalUtil = new TerminalCommandsUtil(newVal, this.$store.state.main.sdk)
    }
  },
  mounted() {
    this.terminalUtil = new TerminalCommandsUtil(this.uuid, this.$store.state.main.sdk)
  },
  methods: {
    detach() {
      this.send_to_terminal = "^C"
      setTimeout(() => {
        this.send_to_terminal = ""
      }, 300)
    },
    prompt: function (val) {
      if (this.terminalUtil.commandExists(val)) {
        this.send_to_terminal = ""
        if (val.includes("-f") && val.includes("logs")) {
          this.subscribeToLogs(this.uuid)
          return
        }
        this.terminalUtil.processCommand(val, this.uuid, this.send_to_terminal).then(res => {
          this.send_to_terminal = res
        })
      } else {
        this.send_to_terminal = ""
        // Else send error message in output of shell
        this.send_to_terminal = `'${val}' is not recognized as an internal command or external`
      }
    },
    subscribeToLogs(uuid) {
      this.terminalUtil.processCommand("logs --tail 100", this.uuid, this.send_to_terminal).then(res => {
        this.send_to_terminal = res
      })
      this.$store.state.main.sdk.logs.subscribe(uuid).then(logs => {
        logs.on("line", (message) => {
          this.terminalUtil.formatMessageAsPromise(message).then(res => {
            this.send_to_terminal += `<br>${res}`
          })
        })
      })
    }
  },
  data() {
    return {
      terminalUtil: undefined,
      services: [],
      currLogs: '',
      history: '',
      send_to_terminal: "",
      banner: {
        header: "",
        subHeader: "Shell for logs from devices",
        helpHeader: 'Enter "help" for more information',
        emoji: {
          first: "",
          second: "",
          time: 750
        },
        sign: "open-balena $",
        img: {
          align: "left",
          link: "",
          width: 0,
          height: 0
        }
      }
    }
  }

}
</script>
<style scoped>
.big {
  min-width: 100%;
}

</style>
